package com.work.yshop.ui.activity;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.tabs.TabLayout;
import com.work.yshop.R;
import com.work.yshop.adapter.OrderAdapter;
import com.work.yshop.model.CartItem;
import com.work.yshop.model.Favorite;
import com.work.yshop.model.Order;
import com.work.yshop.model.ProductHistory;
import com.work.yshop.mvp.contract.UserDataContract;
import com.work.yshop.mvp.presenter.UserDataPresenter;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单列表页面
 */
public class OrderListActivity extends AppCompatActivity implements UserDataContract.View {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private RecyclerView recyclerView;
    private View emptyView;
    private TextView tvEmptyMessage;
    private OrderAdapter adapter;
    private UserDataPresenter presenter;
    
    // 订单状态
    private static final int STATUS_ALL = 0;
    private static final int STATUS_PENDING = 1;
    private static final int STATUS_PROCESSING = 2;
    private static final int STATUS_SHIPPED = 3;
    private static final int STATUS_COMPLETED = 4;
    private static final int STATUS_CANCELED = 5;
    
    private int currentStatus = STATUS_ALL;
    private List<Order> allOrders = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_manage);
        
        // 初始化Presenter
        presenter = new UserDataPresenter(this);
        presenter.attachView(this);
        
        initViews();
        setupToolbar();
        setupTabLayout();
        setupRecyclerView();
        
        // 加载订单数据
        presenter.loadOrderList();
        
        // 获取传入的标签索引
        int tabIndex = getIntent().getIntExtra("tab_index", STATUS_ALL);
        if (tabIndex >= 0 && tabIndex < tabLayout.getTabCount()) {
            tabLayout.selectTab(tabLayout.getTabAt(tabIndex));
        }
    }
    
    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        tabLayout = findViewById(R.id.tab_layout);
        recyclerView = findViewById(R.id.recycler_view);
        emptyView = findViewById(R.id.empty_view);
        tvEmptyMessage = findViewById(R.id.tv_empty_message);
    }
    
    private void setupToolbar() {
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("我的订单");
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
    }
    
    private void setupTabLayout() {
        tabLayout.addTab(tabLayout.newTab().setText("全部"));
        tabLayout.addTab(tabLayout.newTab().setText("待付款"));
        tabLayout.addTab(tabLayout.newTab().setText("待发货"));
        tabLayout.addTab(tabLayout.newTab().setText("待收货"));
        tabLayout.addTab(tabLayout.newTab().setText("已完成"));
        tabLayout.addTab(tabLayout.newTab().setText("已取消"));
        
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                filterOrders(tab.getPosition());
            }
            
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }
    
    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new OrderAdapter();
        recyclerView.setAdapter(adapter);
        
        adapter.setOnItemClickListener(position -> {
            Order order = adapter.getItem(position);
            if (order != null) {
                // 查看订单详情
                // 这里可以跳转到订单详情页面
                Toast.makeText(this, "查看订单: " + order.getOrderNumber(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    /**
     * 根据状态过滤订单
     */
    private void filterOrders(int status) {
        currentStatus = status;
        
        // 根据状态过滤
        List<Order> filteredOrders = new ArrayList<>();
        
        if (status == STATUS_ALL) {
            filteredOrders.addAll(allOrders);
        } else {
            for (Order order : allOrders) {
                if (order.getStatus() == getOrderStatus(status)) {
                    filteredOrders.add(order);
                }
            }
        }
        
        if (filteredOrders.isEmpty()) {
            showEmptyView(status);
        } else {
            showFilteredOrders(filteredOrders);
        }
    }
    
    private int getOrderStatus(int tabPosition) {
        switch (tabPosition) {
            case STATUS_PENDING:
                return Order.STATUS_PENDING;
            case STATUS_PROCESSING:
                return Order.STATUS_PROCESSING;
            case STATUS_SHIPPED:
                return Order.STATUS_SHIPPED;
            case STATUS_COMPLETED:
                return Order.STATUS_COMPLETED;
            case STATUS_CANCELED:
                return Order.STATUS_CANCELED;
            default:
                return 0;
        }
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.detachView();
        }
    }

    // UserDataContract.View接口实现
    @Override
    public void showLoading() {
        // 显示加载中
        emptyView.setVisibility(View.VISIBLE);
        recyclerView.setVisibility(View.GONE);
        tvEmptyMessage.setText("加载中...");
    }

    @Override
    public void hideLoading() {
        // 隐藏加载中
    }

    @Override
    public void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showHistoryList(List<ProductHistory> historyList) {
        // 在订单列表页不需要显示历史列表
    }

    @Override
    public void showFavoriteList(List<Favorite> favoriteList) {
        // 在订单列表页不需要显示收藏列表
    }

    @Override
    public void showCartItems(List<CartItem> cartItems) {
        // 在订单列表页不需要显示购物车列表
    }

    @Override
    public void showOrderList(List<Order> orderList) {
        this.allOrders = orderList;
        filterOrders(currentStatus);
    }

    @Override
    public void showEmptyView(int type) {
        recyclerView.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
        
        switch (currentStatus) {
            case STATUS_PENDING:
                tvEmptyMessage.setText("暂无待付款订单");
                break;
            case STATUS_PROCESSING:
                tvEmptyMessage.setText("暂无待发货订单");
                break;
            case STATUS_SHIPPED:
                tvEmptyMessage.setText("暂无待收货订单");
                break;
            case STATUS_COMPLETED:
                tvEmptyMessage.setText("暂无已完成订单");
                break;
            case STATUS_CANCELED:
                tvEmptyMessage.setText("暂无已取消订单");
                break;
            default:
                tvEmptyMessage.setText("暂无订单");
                break;
        }
    }
    
    private void showFilteredOrders(List<Order> orders) {
        recyclerView.setVisibility(View.VISIBLE);
        emptyView.setVisibility(View.GONE);
        adapter.setData(orders);
    }

    @Override
    public void showResult(boolean success, String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
} 